<!--信息公告-->
<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" style="text-align: left;">
      <el-form-item label="信息内容" prop="text">
        <el-input placeholder="请输入货品名称" v-model="searchForm.text"></el-input>
      </el-form-item>
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="searchForm.type" placeholder="请选择" style="width:180px">
            <el-option v-for="item in types" :key="item.dict_value" :label="item.dict_label" :value="item.dict_label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消息状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择" style="width:180px">
            <el-option v-for="item in status" :key="item.dict_value" :label="item.dict_label" :value="item.dict_value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="search">查询</el-button>
      </el-form-item>
    </el-form>

    <div style="text-align: left;">
        <el-button @click="Export">导出</el-button>
        <el-button @click="DeleteAll">删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" stripe style="margin-top: 10px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed="left"></el-table-column>
      <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
      <el-table-column prop="info_text" label="信息内容" width="700" fixed="left"></el-table-column>
      <el-table-column prop="info_type" label="消息类型"></el-table-column>
      <el-table-column prop="info_status" label="消息状态"></el-table-column>
      <el-table-column prop="info_time" label="接收时间"></el-table-column>
      <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" text @click="ShowInfo(scope.row)">查看</el-button>
                <el-button type="danger" text @click="ShowDelete(scope.row.info_id)">删除</el-button>
            </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :page-size="pageSize"
      :current-page="currentPage"
      layout="prev, pager, next, jumper"
      :total="total"
      @current-change="handlePageChange"
      style="float:right;margin-top:20px"
    />

    <!-- 删除确认模态框 -->
    <el-dialog v-model="DeleteDialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 查看消息详情模态框 -->
    <el-dialog v-model="InfoDialogVisible" width="600" title="消息详情" align-center>
        <div class="info-detail">
            <el-descriptions :column="1">
                <el-descriptions-item label="消息内容">
                    <div class="info-content">{{ currentInfo.info_text }}</div>
                </el-descriptions-item>
                <el-descriptions-item label="消息类型">
                    <el-tag :type="getTypeTagType(currentInfo.info_type)">{{ currentInfo.info_type }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="接收时间">
                    {{ currentInfo.info_time }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="InfoDialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref,reactive,onMounted, computed} from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
  setup() {
        // 搜索表单
        const searchForm = reactive({
            text: '',
            type: '',
            status: '',
        });
        const searchFormRef = ref(null);

    //查询消息类型和消息状态
    const types = ref([]);
    function GetTypes() {
        return http.get("/DictData/GetAllDictDataBytype?typeid=17")
        .then(res => {
            types.value = res.data;
        }).catch(err => {
            console.log(err);
        })
    }

    //查询消息状态
    const status = ref([]);
    function GetStatus() {
        return http.get("/DictData/GetAllDictDataBytype?typeid=16")
        .then(res => {
            status.value = res.data;
        }).catch(err => {
            console.log(err);
        })
    }

        // 状态映射计算属性
         const statusMap = computed(() => {
            const map = {};
            if (status.value && status.value.length > 0) {
                status.value.forEach(item => {
                    map[item.dict_value] = item.dict_label;
                });
            }
            return map;
        });

    // 表格数据
    const tableData = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);

    // 查询方法
    const search = () => {
      fetchData();
    };
    // 重置方法
    const resetSearch = () => {
      searchFormRef.value?.resetFields();
      fetchData();
    };
    // 分页切换
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchData();
    };

    // 获取数据
    const fetchData = () => {
      http.get('/Info/GetInfo', {
        params: {
            text: searchForm.text,
            type: searchForm.type,
            status: searchForm.status,
            CurrentPage:currentPage.value
        }
      }).then(res => {
        tableData.value = res.data.list;
        //转换时间并计算百分比，状态映射
        tableData.value.forEach(item => {
            item.info_time = formatDateTime(new Date(item.info_time));
            item.info_status = statusMap.value[item.info_status] || "未知状态";
        });
        total.value = res.data.rows;
      }).catch(err => {
        console.log(err.data);
      });
    };


    //选中的数据
    const selectdata = ref([]);
    const handleSelectionChange = (val) => {
      selectdata.value = val;
    };
    //导出
    function Export(){
      if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "序号": row.info_id,
                "信息内容": row.info_text,
                "消息类型": row.info_type,
                "消息状态": row.info_status,
                "接收时间": row.info_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "消息信息");
            // 导出并下载
            XLSX.writeFile(wb, `消息信息${new Date().toLocaleDateString()}.xlsx`);
    }


     // 时间转换
    function formatDateTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }


    // 删除相关
    const DeleteDialogVisible = ref(false);
    const currentDeleteId = ref(0);

    // 查看详情相关
    const InfoDialogVisible = ref(false);
    const currentInfo = ref({});

    // 显示删除确认框
    const ShowDelete = (id) => {
        currentDeleteId.value = id;
        DeleteDialogVisible.value = true;
    };

    // 删除单条消息
    const Delete = async () => {
        try {
            const res = await http.delete(`/Info/DeleteInfo?id=${currentDeleteId.value}`);
            if (res.data > 0) {
                ElMessage.success('删除成功');
                DeleteDialogVisible.value = false;
                fetchData(); // 刷新数据
            } else {
                ElMessage.error('删除失败');
            }
        } catch (err) {
            console.error(err);
            ElMessage.error('删除失败');
        }
    };

    // 批量删除
    const DeleteAll = () => {
        if (selectdata.value.length === 0) {
            ElMessage.warning('请选择要删除的数据');
            return;
        }
        
        ElMessageBox.confirm(`确定要删除选中的 ${selectdata.value.length} 条消息吗？`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            try {
                const deletePromises = selectdata.value.map(item => {
                    return http.delete(`/Info/DeleteInfo?id=${item.info_id}`);
                });
                
                const results = await Promise.all(deletePromises);
                const successCount = results.filter(res => res.data > 0).length;
                
                if (successCount === selectdata.value.length) {
                    ElMessage.success(`成功删除 ${successCount} 条数据`);
                } else {
                    ElMessage.warning(`成功删除 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                }
                
                fetchData(); // 刷新数据
            } catch (err) {
                console.error(err);
                ElMessage.error('批量删除失败');
            }
        }).catch(() => {
            ElMessage.info('已取消删除');
        });
    };

    // 显示消息详情
    const ShowInfo = (row) => {
        currentInfo.value = { ...row };
        InfoDialogVisible.value = true;
        //修改状态
        http.put(`/Info/UpdateStatus?id=${row.info_id}&status=1`);
        fetchData();
    };

    // 获取消息类型标签样式
    const getTypeTagType = (type) => {
        return 'warning';
    };

    const route = useRoute();

    onMounted(() => {
        GetStatus().then(() => {
            // 检查是否有类型参数
            const typeParam = route.query.type;
            if (typeParam) {
                searchForm.value.info_type = typeParam;
            }
            fetchData();
        });
        GetTypes();
    });


    return {
      searchForm,
      searchFormRef,
      types,
      tableData,
      total,
      pageSize,
      currentPage,
      search,
      resetSearch,
      handlePageChange,
      Export,
      handleSelectionChange,
      selectdata,
      types,
      status,
      // 新增的功能
      DeleteDialogVisible,
      InfoDialogVisible,
      currentInfo,
      ShowDelete,
      Delete,
      DeleteAll,
      ShowInfo,
      getTypeTagType
    };
  }
};
</script>

<style scoped>
/* 预警状态样式 */
.warning-text {
  color: #ff4d4f;
  font-weight: bold;
}

.normal-text {
  color: #52c41a;
}

.excess-text {
  color: #fa8c16;
  font-weight: bold;
}

/* 表格行样式 */
:deep(.el-table .warning-row) {
  background: #fff2f0;
}

:deep(.el-table .excess-row) {
  background: #fff7e6;
}

/* 消息详情样式 */
.info-detail {
  padding: 20px 0;
}

.info-content {
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
  word-break: break-all;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}


/* 描述列表样式 */
:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  width: 100px;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>
